package cn.wolfcode.wolf2w.listener;


import cn.wolfcode.wolf2w.cache.util.RedisKeys;
import cn.wolfcode.wolf2w.domain.Strategy;
import cn.wolfcode.wolf2w.cache.vo.StrategyStatisVO;
import cn.wolfcode.wolf2w.service.IStrategyService;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.StringUtils;

import java.util.List;

//@Component (扫描监听器 初始化)
public class RedisDataInitListener implements ApplicationListener<ContextRefreshedEvent>{
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private IStrategyService strategyService;

    // 当容器调用refresh（）方法时候马上执行下面逻辑
    // spring容器启动后，并初始化完成之后马上执行下面逻辑
    @Override
    public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
        System.out.println("初始化star-----------------------------");

        // 查询mongodb数据库中所有攻略
        List<Strategy> strategyList = strategyService.list();
        // 将攻略对象转化成vo
        for (Strategy strategy : strategyList){
            String key = RedisKeys.STRATEGY_STATIS_VO.join(strategy.getId());
            String voStr = stringRedisTemplate.opsForValue().get(key);
            // 需要考虑第二次初次化时会把最新的数据进行覆盖操作,还原原来的旧数据
            // 判断是否存在vo
            if (StringUtils.hasLength(voStr)){
                continue;
            }
            // 把vo对象保存到redis中
            StrategyStatisVO vo = new StrategyStatisVO();
            BeanUtils.copyProperties(strategy,vo);
            vo.setStrategyId(strategy.getId());
            stringRedisTemplate.opsForValue().set(key, JSON.toJSONString(vo));
        }
        System.out.println("初始化end-----------------------------");

    }
}
